#include <iostream>
#include <vector>
#include <queue>

using namespace std;

bool isSafe(vector<vector<int>>& allocation, vector<vector<int>>& maxNeed, vector<int>& available) 
{
    int numP = allocation.size();
    int numR = available.size();
    vector<bool> finish(numP, false);
    vector<int> work = available;
    queue<int> sq;

    while (true) 
    {
        bool found = false;
        for (int i = 0; i < numP; ++i) 
        {
            if (!finish[i]) 
            {
                bool can = true;
                for (int j = 0; j < numR; ++j) 
                {
                    if (maxNeed[i][j] - allocation[i][j] > work[j]) 
                    {
                        can = false;
                        break;
                    }
                }
                if (can) 
                {
                    for (int k = 0; k < numR; ++k) 
                    {
                        work[k] += allocation[i][k];
                    }
                    finish[i] = true;
                    found = true;
                    sq.push(i);
                }
            }
        }
        if (!found) break;
    }

    if (sq.size() == numP) 
    {
        cout << "系统处于安全状态。" << endl;
        cout << "安全序列：";
        while (!sq.empty()) 
        { 
            if(sq.size()==1)          
            cout << sq.front();
            else cout<<sq.front()<<", ";
            sq.pop();
        }
        cout << endl;
        return true;
    }
    else 
    {
        cout << "系统处于不安全状态。" << endl;
        return false;
    }
} 


int main()
{
    vector<int> available;
    vector<vector<int>> maxNeed, allocation;
    int numR;
    int numP;
    cin >> numR;
    for (int i = 0; i < numR; i++)
    {
        int x; cin >> x;
        available.push_back(x);
    }
    cin >> numP;
    for (int i = 0; i < numP; i++)
    {
        vector<int> row;
        for (int j = 0; j < numR; j++)
        {
            int num; cin >> num;
            row.push_back(num);
        }
        maxNeed.push_back(row);
    }

    for (int i = 0; i < numP; i++)
    {
        vector<int> row;
        for (int j = 0; j < numR; j++)
        {
            int num; cin >> num;
            row.push_back(num);
        }
        allocation.push_back(row);
    }

    isSafe(allocation, maxNeed, available);

    return 0;
}